package com.myipinfo;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;

import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import android.widget.TextView;

public class MainActivity extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		MyThread myThread = (MyThread) new MyThread().execute((Void) null);

		try {
			Map<String, String> map = myThread.get();

			TextView ipView = (TextView) findViewById(R.id.ipView);
			ipView.setText(map.get("addr"));

			TextView countryView = (TextView) findViewById(R.id.countryView);
			countryView.setText(map.get("country"));

			String sResult = "";
			TextView testView = (TextView) findViewById(R.id.testView);

			ConnectivityManager conManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);

			// NetworkInfo[] ani = mgr.getAllNetworkInfo();
			// for (NetworkInfo n : ani) {
			// sResult += (n.toString() + "\n\n");
			// }

			NetworkInfo ni = conManager.getActiveNetworkInfo();

			if (ni != null) {
				sResult += ("Active : \n" + ni.toString() + "\n");
				testView.setText(sResult);
			}

			TextView testView2 = (TextView) findViewById(R.id.testView2);
			Log.i("localIP", getLocalIPAddress());
			testView2.setText(getLocalIPAddress());

		} catch (Exception e) {
			Log.e("err", e.toString());
		}

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	public static InputStream getInputStreamFromUrl(String url) {
		Log.i("getInputStreamFromUrl", "getInputStreamFromUrl start");
		InputStream contentStream = null;
		try {
			HttpClient httpclient = new DefaultHttpClient();
			HttpResponse response = httpclient.execute(new HttpGet(url));

			contentStream = response.getEntity().getContent();

		} catch (Exception e) {
			e.printStackTrace();
		}
		Log.i("getInputStreamFromUrl", "getInputStreamFromUrl end");
		return contentStream;
	}

	public class MyThread extends AsyncTask<Void, Void, Map<String, String>> {

		@Override
		protected Map<String, String> doInBackground(Void... params) {
			Map<String, String> map = new HashMap<String, String>();

			try {
				String rtn = getStringFromUrl("http://115.71.238.29:8080/IpInfo/IpInfo.do");
				Log.i("rtn", rtn);

				JSONArray jsonArray = new JSONArray(rtn);
				map.put("addr", jsonArray.getJSONObject(0).getString("addr"));
				map.put("country",
						jsonArray.getJSONObject(0).getString("country"));

			} catch (Throwable t) {
				// TODO: handle exception

			}

			return map;
		}

		@Override
		protected void onProgressUpdate(Void... values) {
			// TODO Auto-generated method stub
			super.onProgressUpdate(values);
		}

		public String getStringFromUrl(String url)
				throws UnsupportedEncodingException {
			BufferedReader br = new BufferedReader(new InputStreamReader(
					getInputStreamFromUrl(url), "UTF-8"), 8);
			StringBuffer sb = new StringBuffer();
			try {
				String line = null;

				while ((line = br.readLine()) != null) {
					sb.append(line);
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			return sb.toString();
		}

	}

	public String getLocalIPAddress() {
		final String IP_NONE = "N/A";
		final String WIFI_DEVICE_PREFIX = "eth";

		String localIP = IP_NONE;
		try {
			NetworkInterface.getNetworkInterfaces();
			for (Enumeration<NetworkInterface> en = NetworkInterface
					.getNetworkInterfaces(); en.hasMoreElements();) {
				NetworkInterface intf = en.nextElement();
				for (Enumeration<InetAddress> enumIpAddr = intf
						.getInetAddresses(); enumIpAddr.hasMoreElements();) {
					InetAddress inetAddress = enumIpAddr.nextElement();
					if (!inetAddress.isLoopbackAddress()) {
						if (localIP.equals(IP_NONE))
							localIP = inetAddress.getHostAddress().toString();
						else if (intf.getName().startsWith(WIFI_DEVICE_PREFIX))
							localIP = inetAddress.getHostAddress().toString();
					}
				}
			}
		} catch (Exception e) {
			// TODO: handle exception
			Log.e("MainActivity.class",
					"getLocalIpAddress Exception:" + e.toString());
		}

		return localIP;
	}

}
